import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:wechat_kit/wechat_kit.dart';

typedef WechatAuthRespListener = void Function(WechatAuthResp response);
typedef WechatPayRespListener = void Function(WechatPayResp response);
typedef WechatSdkRespListener = void Function(WechatSdkResp response);

class WechatBuilder extends StatefulWidget {
  final Wechat wechat;
  final WidgetBuilder builder;
  final WechatAuthRespListener authRespListener;
  final WechatPayRespListener payRespListener;
  final WechatSdkRespListener sdkRespListener;

  final String appId;
  final String universalLink;

  const WechatBuilder({
    @required this.wechat,
    @required this.builder,
    this.authRespListener,
    this.payRespListener,
    this.sdkRespListener,
    @required this.appId,
    this.universalLink,
  });

  @override
  State<StatefulWidget> createState() {
    return _WechatBuilderState();
  }
}

class _WechatBuilderState extends State<WechatBuilder> {
  StreamSubscription<WechatAuthResp> _authRespSubscription;
  StreamSubscription<WechatPayResp> _payRespSubscription;
  StreamSubscription<WechatSdkResp> _sdkRespSubscription;

  @override
  void initState() {
    super.initState();

    widget.wechat.registerApp(
      appId: widget.appId,
      universalLink: widget.universalLink,
    );
    if (widget.authRespListener != null) {
      _authRespSubscription = widget.wechat.authResp().listen(widget.authRespListener);
    }
    if (widget.payRespListener != null) {
      _payRespSubscription = widget.wechat.payResp().listen(widget.payRespListener);
    }
    if (widget.sdkRespListener != null) {
      _sdkRespSubscription = widget.wechat.shareMsgResp().listen(widget.sdkRespListener);
    }
  }

  @override
  void dispose() {
    _authRespSubscription?.cancel();
    _payRespSubscription?.cancel();
    _sdkRespSubscription?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context);
  }
}
